import os

# 定义C++代码模板，用于插入Lua脚本内容
cpp_template = """
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include "global.h"

namespace LuaHelp {
    sol::table open_luaGlobal(sol::this_state L) {
        sol::state_view lua(L);

        // 拼接分段后的Lua脚本
        std::string lua_code;
        %s
        sol::table module = lua.script(lua_code);
        return module;
    }
}

extern "C" int luaopen_luaParametersSweep(lua_State* L) {
    return sol::stack::call_lua(L, 1, LuaHelp::open_luaGlobal );
}
"""

# 读取Lua脚本文件内容
lua_file_path = "../../../lua/luaParametersSweep.lua"
with open(lua_file_path, "r", encoding="utf-8") as file:
    lua_script = file.read()

# 将Lua脚本内容分割为不超过300字符的片段，按行分割
def split_long_string_by_line(script, max_length=1000):
    segments = []
    current_segment = ""
    
    for line in script.splitlines(keepends=True):  # 保持行末尾
        # 检查添加当前行后是否超出最大长度限制
        if len(current_segment) + len(line) > max_length:
            segments.append(f'R"({current_segment})"')
            current_segment = line  # 启动新段
        else:
            current_segment += line
    
    if current_segment:  # 追加最后一个段
        segments.append(f'R"({current_segment})"')
    
    return segments

# 调用函数并生成段落列表
lua_segments = split_long_string_by_line(lua_script)

# 将每个段落转换为lua_code拼接形式
lua_code_segments = "\n".join([f'lua_code += {seg};' for seg in lua_segments])

# 将分段后的Lua脚本插入C++模板
final_cpp_code = cpp_template % lua_code_segments

# 输出生成的C++代码到文件
output_file_path = "../luaParametersSweep/global.cpp"
with open(output_file_path, "w", encoding="utf-8") as file:
    file.write(final_cpp_code)

print("Successfully generated global.cpp with segmented Lua script content.")
